package org.kalai.unifypay.tfb.pay;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.kalai.unifypay.util.CipherUtils;
import org.kalai.unifypay.util.StringUtil;

public class TFBUtils {

   private static final Logger logger = Logger.getLogger(TFBUtils.class);

   /**
    * 加入协议参数(内有签名)
    * 
    * @param params
    * @param keyName
    * @return
    */
   public static TreeMap<String, Object> sign(TreeMap<String, Object> params, String secretKey) {
      try {
         StringBuffer buf = new StringBuffer();
         for (Map.Entry<String, Object> param : params.entrySet()) {
            if (!"".equals(param.getValue())) {
               buf.append(param.getKey()).append("=").append(param.getValue()).append("&");
            }
         }
         buf.append("key=" + secretKey);// 最后加上秘钥秘钥
         params.put("input_charset", "UTF-8");// 字符集
         params.put("sign", Md5Util.getMD5(buf.toString()));// 签名
         return params;
      } catch (Exception e) {
         logger.error("加入协议参数异常:" + e);
         return null;
      }
   }

   /**
    * 验证签名
    * 
    * @param params
    * @return
    */
   public static boolean verifySign(TreeMap<String, String> params, String secretKey, String sign) {
      try {
         StringBuffer paramstr = new StringBuffer();
         for (String pkey : params.keySet()) {
            String pvalue = params.get(pkey);
            if (StringUtil.isEmpty(pvalue)||pkey.equals("sign")||pkey.equals("retcode")|| pkey.equals("retmsg")||pkey.equals("sign_type")) {// 空值不传递，不签名
               continue;
            }
            paramstr.append(pkey + "=" + pvalue + "&"); // 签名原串，不url编码
         }
         paramstr.append("key=" + secretKey);// 最后加上秘钥秘钥
         return sign.equalsIgnoreCase(Md5Util.getMD5(paramstr.toString(), "GBK"));
      } catch (Exception e) {
         logger.error("验证签名异常:" + e);
         return false;
      }
   }
   public static void main(String[] args) {
      String a="item_name=zsl-测试&listid=1021800776625161020000023304&notify_type=1&pay_type=800201&sp_billno=OR1020173906065168437&sysd_time=20161020173929&tran_amt=10&tran_state=1&tran_time=20161020053906&key=12345";
      System.err.println(CipherUtils.encryptMD5(a));
   }
   /**
    * xml转换map
    * 
    * @param xml
    *           xml字符串
    * @return
    * @throws DocumentException
    */
   public static TreeMap<String, String> xmlToMap(String xml) {
      TreeMap<String, String> map = new TreeMap<String, String>();
      try {
         Document doc = DocumentHelper.parseText(xml);
         if (doc == null)
            return map;
         Element root = doc.getRootElement();
         for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
            Element e = (Element) iterator.next();
            List list = e.elements();
            map.put(e.getName(), e.getText());
         }
      } catch (Exception e) {
         logger.error("xml转换map异常:" + e);
         return map;
      }
      return map;
   }

   /**
    * 解析xml
    */
   public static String getXmlElement(String responseData, String element) {
      String result = null;

      try {
         Document dom = DocumentHelper.parseText(responseData);
         Element root = dom.getRootElement();
         result = root.element(element).getText();
      } catch (DocumentException e1) {
         e1.printStackTrace();
      }
      return result;
   }
}
